--------------------------------------------------------------------------------
---  @Project:   KappaFramework
---  @FileName:  server.lua
---  @Author:    xxx_xxx@xxx.co.jp
---  @Brief:     
---  @Date:
--------------------------------------------------------------------------------

require"utils"
local socket = require"socket"
local copas = require"copas"
local assert = assert
local require = require
local printf = printf
local pcall = pcall
local weaktable = weaktable
module(...)

service = function(app)
  assert(app,"passed application is not defined")
  app.sessions = weaktable{}
  --Attach the Apps filter to the server's handler function
  handler   = function(skt)
    app.continue = true
    while app.continue==true do
      local data = copas.receive(skt,app.breakpattern)
      if (data==nil)then
        -->continue
        break
      else
        local reply = "ok"
        local callok = false
        app.sessions[skt] = app.sessions[skt] or {} 
        callok, app.continue, reply = pcall(app.filter,data,app.sessions[skt]) -->We attach the filter here
        if callok ~= true then
          printf("failed handler")
          app.continue = true --we failed but don't bail out
          reply = "error"
        end
        printf("reply:\t%s",reply or "error")
        copas.send(skt, (reply).."\n")
      end  
    end
  end
  
  app.hndserver = assert(socket.bind(app.ip,app.port))-->create a new server
  if app.hndserver then
    copas.addserver(app.hndserver, handler)
    printf("Create service, success:%s",app.name)
  else
    return nil,"Create service, failure"
  end
  printf("Connected Service:%s[%s:%s]",app.name,app.ip,app.port)
  app.continue = true  
  while app.continue do 
    copas.step(app.frequency) --loop every X seconds
  end
  return "Terminated Service"
end

--- Demo Structure -------------------------------------------------------------
-- This is what a sample service object looks like
myapp = {
  name      = "demo",
  hndServer = nil, -->The service will assign a handler here
  ip        = "localhost",
  port      = 666,
  frequency = 1, -->seconds
  filter    = function(data) -->all incomming data will pass through this filter
    if (data == "shutdown") then
      return false, "shutdown\n"
    else
      print(data) 
      return true, "ok\n"
    end
  end,
}
--------------------------------------------------------------------------------

--- Usage ----------------------------------------------------------------------
--  Service(MyApp)
--------------------------------------------------------------------------------























--------------------------------------------------------------------------------
--  EOF
--------------------------------------------------------------------------------
